package cn.edu.sdjzu.xg.bysj.dao;

import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisor;
import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisorEntry;
import util.JdbcHelper;

import java.sql.*;


public class ApplicationForSupervisorDao {
    private static ApplicationForSupervisorDao  applicationForSupervisorDao =
            new ApplicationForSupervisorDao ();


    private ApplicationForSupervisorDao() {
    }

    public static ApplicationForSupervisorDao getInstance() {
        return applicationForSupervisorDao;
    }

    public static boolean add(ApplicationForSupervisor applicationForSupervisor, Connection connection) throws SQLException {
        //创建sql语句
        String addApplicationForSupervisor_sql =
                "insert into ApplicationForSupervisor (selfIntroduction,year,student_id) values " +
                        "(?,?,?)";

        PreparedStatement pstmt = connection.prepareStatement(addApplicationForSupervisor_sql, Statement.RETURN_GENERATED_KEYS);

            //为添加ApplicationForSupervisor表的预编译语句赋值
            pstmt.setString(1,applicationForSupervisor.getSelfIntroduction());
            pstmt.setInt(2,applicationForSupervisor.getYear());
            pstmt.setInt(3,applicationForSupervisor.getStudent().getId());
            int idOfAddedApplicationForSupervisor = 0;
            int affectedRowNum = pstmt.executeUpdate();
            //获取新增对象id并为applicationForSupervisor赋值
            ResultSet resultSet = pstmt.getGeneratedKeys();
            if (resultSet.next()) {
                //读取第一个
                idOfAddedApplicationForSupervisor = resultSet.getInt(1);
                applicationForSupervisor.setId(idOfAddedApplicationForSupervisor);
            }
          JdbcHelper.close(resultSet,null);
        for(ApplicationForSupervisorEntry c:applicationForSupervisor.getApplicationForSupervisorEntries()){
            String addApplicationForSupervisorEntry_sql =
                    "insert into ApplicationForSupervisorEntry (priority,teacher_id,applicationForSupervisor_id) values " +
                            "(?,?,?);";
            PreparedStatement pstmt2 = connection.prepareStatement(addApplicationForSupervisorEntry_sql);
            //在该链接上创建预编译语句对象
            pstmt2.setInt(1,c.getPriority());
            pstmt2.setInt(2,c.getTeacher().getId());
            pstmt2.setInt(3,idOfAddedApplicationForSupervisor);
            int affectedRowNum2 = pstmt2.executeUpdate();
            JdbcHelper.close(pstmt2,null);

        }

        JdbcHelper.close(pstmt,null);
        if (affectedRowNum  == 0) {
            return false;
        }
        return true;
    }
}
